# -*- coding: utf-8 -*-

#
# peerscape.http.controllers.application
#
# Copyright 2008 Helsinki Institute for Information Technology
# and the authors.
#
# Authors:
#       Konrad Markus <konrad.markus@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from __future__ import with_statement

from webob import Response
from webob.exc import HTTPMovedPermanently, HTTPBadRequest, HTTPNotFound, HTTPOk
from peerscape.http.controllers import BaseController
from peerscape.profile.application import create_content_from_application
from mako import exceptions

class Application(BaseController):
    def index(self, req):
        # check the type before proceeding
        redir_url = self.require_type(req, ['application'])
        if redir_url:
            return HTTPMovedPermanently(location=redir_url)

        view = self.load_view('application.html')
        if view:
            v = {}
            db = req.environ['peerscape.db']
            self.init_translation(db)
            v['global_props'] = self.get_global_props(db)
            v['hexlabel'] = req.urlvars['peerscape.hexlabel']
            
            v['application'] = self.process_application_profile(db, v['hexlabel'])

            # make it so
            return view.render(**v)
        else:
            return None

    def create(self, req):
        if req.method == 'POST':
            view = self.load_view('application.create.html')
            if view:
                v = {}
                db = req.environ['peerscape.db']
                self.init_translation(db)
                v['global_props'] = self.get_global_props(db)
                v['errors'] = False
                v['message'] = ''
                v['errors_group'] = False
                v['message_group'] = ''
                v['my_iid'] = db.get_my_iid()
                v['group_list'] = self.process_group_links_list(db, v['my_iid'], v['my_iid'])
                v['hexlabel'] = req.urlvars['peerscape.hexlabel']
                v['application'] = self.process_application_profile(db, v['hexlabel'])

                v['dirty'] = {}
                v['dirty']['title'] = ''
                v['dirty']['public'] = ''
                v['dirty']['accept'] = ''
                v['dirty']['title_group'] = ''
                v['dirty']['public_group'] = ''
                v['dirty']['accept_group'] = ''

                add_to_group = req.POST.get('add_to_group') 
                public_link = req.POST.get('public_link')
                if public_link == 'yes':
                    public_link = True
                else:
                    public_link = False

                if not req.POST.get('appiid'):
                    if add_to_group:
                        v['errors_group'] = True
                        v['message_group'] = _('An error has occured. Please try again later.')
                    else:
                        v['errors'] = True
                        v['message'] = _('An error has occured. Please try again later.')
                    return view.render(**v)

                if not req.POST.get('title'):
                    if add_to_group:
                        v['dirty']['public_group'] = public_link
                        v['dirty']['accept_group'] = accept
                        v['errors_group'] = True
                        v['message_group'] = _('Please enter a title')
                    else:
                        v['dirty']['public'] = public_link
                        v['dirty']['accept'] = accept
                        v['errors'] = True
                        v['message'] = _('Please enter a title')
                    return view.render(**v)

                if add_to_group and (not req.POST.get('group') or req.POST.get('group') == 'null'):
                    v['dirty']['title_group'] = req.POST.get('title')
                    v['dirty']['public_group'] = public_link
                    v['dirty']['accept_group'] = accept
                    v['errors_group'] = True
                    v['message_group'] = _('Please select a group')
                    return view.render(**v)

                appiid = req.POST.get('appiid')
                title = req.POST.get('title')

                # create the content
                if add_to_group:
                    giid = str(req.POST.get('group'))
                    c = create_content_from_application(db, appiid, title, giid, public_link=public_link)
                else:
                    c = create_content_from_application(db, appiid, title, v['my_iid'], public_link=public_link)

                # redirect to new content
                redir_url = 'http://%s.hexlabel.net/' % c
                return HTTPMovedPermanently(location=redir_url)
        else:
            # GET
            view = self.load_view('application.create.html')
            if view:
                v = {}
                db = req.environ['peerscape.db']
                self.init_translation(db)
                v['global_props'] = self.get_global_props(db)
                v['hexlabel'] = req.urlvars['peerscape.hexlabel']
                v['application'] = self.process_application_profile(db, v['hexlabel'])
                v['my_iid'] = db.get_my_iid()
                v['group_list'] = self.process_group_links_list(db, v['my_iid'], v['my_iid'])

                v['dirty'] = {}
                v['dirty']['title'] = ''
                v['dirty']['public'] = 'no'
                v['dirty']['accept'] = ''
                v['dirty']['title_group'] = ''
                v['dirty']['public_group'] = 'no'
                v['dirty']['accept_group'] = ''

                # make it so
                return view.render(**v)
            else:
                return None


